package study07;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatClient extends  JFrame{
			//构造属性和初始化
	        private JTextArea  jta;
	        private JTextField  jtf;
	        private JButton  jb;
	        private JLabel name;
	        private Socket s;
	        private PrintWriter pw;
	        private  BufferedReader br;
	        private  DateFormat format;
	        private Date date = new Date();
	        public  ChatClient(){
	        		this.setSize(300,350);
	        		this.setTitle("chat");
	        		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        		jta  = new JTextArea(15,20);
	        		jtf  = new JTextField(15);
	        		jb = new JButton("发送");
	        		name = new JLabel("");
	        		JPanel jp = new JPanel();
	        		jp.setLayout(new FlowLayout());
	        		jp.add(name);
	        		jp.add(jtf);
	        		jp.add(jb);
	        		jb.addActionListener(new SendMsg());
	        		this.setLayout(new BorderLayout());
	        		this.add(jta,BorderLayout.CENTER);
	        		this.add(jp,BorderLayout.SOUTH);
	        		getMsg();
	        		this.setVisible(true);
	        }
	        //接收信息的方法
	        public void getMsg(){
	        	   try {
					s = new Socket("127.0.0.1",8888);
					pw = new PrintWriter(s.getOutputStream());
					new ClientThread().start();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        class ClientThread extends Thread{
	        			@Override
	        			public void run() {
	        				// TODO Auto-generated method stub
	        				while (true) {
	        					
								try {
									br = new BufferedReader(new InputStreamReader(s.getInputStream()));
									jta.append(br.readLine()+"\n");
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} 
							}
	        			}
	        }
	        class SendMsg implements  ActionListener{

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					format  = DateFormat.getTimeInstance();
					String time = format.format(date);
					pw.println(time+name.getText()+"说:"+jtf.getText()+"\n");
					pw.flush();
					jtf.setText("");
				}
	        	
	        }
	        public static void main(String[] args) {
				  new ChatClient();
			}
	        
}
